﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using UE.SharePoint.ImportExport.BLL;
using System.Web.UI;
using System.Text;
using Microsoft.SharePoint.Utilities;
using System.Globalization;
using UE.SharePoint.ImportExport.Resources;
using Microsoft.SharePoint.Administration;

namespace UE.SharePoint.ImportExport.Layouts
{
    /// <summary>
    /// 
    /// </summary>
    public partial class UploadPage : LayoutsPageBase
    {
        private string listId = string.Empty;
        private string isDlg = string.Empty;

        /// <summary>
        /// page load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.UploadButton.Click += new EventHandler(UploadButton_Click);

            listId = Request.QueryString["listId"];
            if (!Util.ValidateSPlistExist(SPContext.Current.Web, listId))
            {
                Response.Write("ListId 不正确！");
                Response.End();
            }

            listId = listId.Replace("{", "").Replace("}", "");
            isDlg = Request.QueryString["isDlg"];
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            litPageDescription.Text = ImportExportResource.UploadPage_Description;
            UploadButton.Text = ImportExportResource.UploadPage_Ok;
            UploadCancelButton.Text = ImportExportResource.UploadPage_Cancel;
            litNameDescription.Text = ImportExportResource.UploadPage_Name;
            UploadPageTilte.Text = ImportExportResource.UploadPage_Title;
            (this.UploadSection as InputFormSection).Title = ImportExportResource.UploadPage_NameTitle;
            (this.UploadSection as InputFormSection).Description = ImportExportResource.UploadPage_NameDescription;
        }

        /// <summary>
        /// start to upload
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void UploadButton_Click(object sender, EventArgs e)
        {
            //validate
            if (!UploadExcel.HasFile)
            {
                FileError.Text = "You need to select an Excel spreadsheet file first.";
                return;
            }

            ImportManager importManager = new ImportManager();
            SPSite spSite = SPContext.Current.Site;
            SPWeb spWeb = SPContext.Current.Web;
            string resultInfomation = string.Empty;
             
            //upload to web folder  
            SPFolder rootFolder = spWeb.Lists[new Guid(listId)].RootFolder;
            string strFolder = rootFolder.Url + "/Upexcel";
            SPFolder spFolder = spWeb.GetFolder(strFolder);
            string fileExt = UploadExcel.FileName.Substring(UploadExcel.FileName.LastIndexOf(".") + 1);
            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + "." + fileExt;

            if (!spFolder.Exists)
            {
                spFolder = rootFolder.SubFolders.Add(strFolder);
            }
            spFolder.Files.Add(fileName, UploadExcel.FileBytes);
            WorkStatus status = new WorkStatus();
            status.LogFormat = ImportExportResource.ImportErrorFormat;

#if !DEBUG   
            try
            {
#endif
                if (importManager.Execute(SPContext.Current.Site, SPContext.Current.Web, listId, strFolder, fileName, status))
                {
                    resultInfomation = FormatMessage(resultInfomation, status);
                }
                else
                {
                    resultInfomation = "Sorry,Upload failed！";
                }
#if !DEBUG   
            }
            catch(Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("ImportExport", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
                resultInfomation = "Upload failed！System Error！";
            }
#endif

                Page.ClientScript.RegisterStartupScript(this.GetType(), "infomation", "<script>showResult(\"" + resultInfomation + "\");</script>");
        }

        /// <summary>
        /// Format the output message
        /// </summary>
        /// <param name="resultInfomation"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        private static string FormatMessage(string resultInfomation, WorkStatus status)
        {
            string result = string.Empty;
            string details = string.Empty;
            foreach (var statusItem in status.Messages)
            {
                details += statusItem.Message.Replace("\n", "") + "\\n";
            }

            result = string.Format(ImportExportResource.ImportResultFormat, status.ProcessedNum, status.SucceedNum, status.FailedNum, details);

            return result;
        }
    }
}
